package com.mcgrobot.plugin.dynamicds;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 *实现动态选择数据源的拦截器，拦截添加了从库数据源的注解方法，将当前的数据源切换为从库
 */
@Aspect
public class DataSourceAspect {

    private static Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);

    @Pointcut("@annotation(com.mcgrobot.plugin.dynamicds.SlaveDataSource)")
    public void aspect() {}

    @Before("aspect()")
    public void doBefore(JoinPoint point) throws Throwable {
        final MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        SlaveDataSource slaveDataSource = method.getAnnotation(SlaveDataSource.class);
        if (slaveDataSource != null) {
            logger.info("切换为从库,类为:{},业务方法为:{}",method.getDeclaringClass().getName(), method.getName());
            DataSourceRouteHolder.setSlaveDataSource();
        }
    }

    @After("aspect()")
    public void doAfter(JoinPoint point) {
        final MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        logger.info("清除掉从库数据源设置,类为:{},业务方法为:{}",method.getDeclaringClass().getName(), method.getName());
        DataSourceRouteHolder.clearDataSourceKey();
    }

    @AfterThrowing("aspect()")
    public void afterThrowing(JoinPoint jp) throws Throwable {
        doAfter(jp);
    }

}
